<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input id="fileInput" type="file" />
    <img id="newImg" src="" alt="">
  </body>
  <script>
    /*
        1. 监听文件输入事件获取文件
        2. 利用文件流将文件转换为base64格式字符串
        3. 通过canvas把原来的图片重画一遍，
        利用canvas执行上下文toDataURL方法的第二参数将图片百分比压缩

        // 补充：个人写过一篇相关博客，https://juejin.cn/post/7081619017365979149
    */   
    let inputFile = document.getElementById("fileInput");
    // 监听文件输入事件
    inputFile.onchange = function (e) {
      let file = e.target.files[0]; 
      fileToBase64(file, 0.2);
    };
    //通过文件流将文件转换成Base64字符串  
    const fileToBase64 = async (file, quality) => {
      let type = file.type; //"image/png"
      let fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      // 文件加载完执行   
      fileReader.onload = function (e) {
        let base64Str = fileReader.result
        // 执行压缩函数
        compress(base64Str, quality, type);
      };
    };
    // 压缩函数：通过把图片重画一遍，之后用画布toDataURL按百分数压缩
    const compress = (base64, quality, mimeType) => {
      let img = new Image();
      img.crossOrigin = "anonymous";
      img.src = base64;
      // base64格式的图片加载完执行   
      img.onload = () => {
        let cvs = document.createElement("canvas");
        // 给画布设置大小
        cvs.width = img.width
        cvs.height = img.height
        // 获取画布执行上下文
        let ctx = cvs.getContext("2d")
        // 开始重新绘制一样的图片
        ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
        // 将图片按百分数压缩
        let imageData =  cvs.toDataURL(mimeType, quality);
        document.getElementById('newImg').src = imageData
      }
    };
  </script>
</html>
